package com.bawei.module_mine.viewmodel

import androidx.lifecycle.viewModelScope
import com.bawei.library_mvi.model.BaseViewModel
import com.bawei.module_mine.intent.LoginIntent
import com.bawei.module_mine.model.service.LoginService
import com.bawei.module_mine.state.LoginState
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.flow.*
import kotlinx.coroutines.launch

/**
 * @Author : yaotianxue
 * @Time : On 2023/6/26 15:46
 * @Description : LoginViewModel
 */
class LoginViewModel:BaseViewModel<LoginIntent>() {
    private val service:LoginService by lazy{LoginService()}
    private val _states = MutableStateFlow<LoginState>(LoginState.loginInit)
    val states:StateFlow<LoginState>
        get() = _states


    override fun handleIntent() {
        //GlobalScope 内存泄漏生命周期问题 当app销毁的时候，结束，不建议使用
        //viewModelScope 当viewmodel结束，
        //lifecycleScope：当fragment/activity销毁的时候，结束

        viewModelScope.launch {
            intents.consumeAsFlow().collect{
                when(it){
                    is LoginIntent.Login -> doLogin(it)
                }
            }
        }
    }

    private fun doLogin(it: LoginIntent.Login) {
        viewModelScope.launch {
            flow{
                val responseEntity = service.login(it.username, it.password)
                emit(responseEntity)
            }.catch { e->//登陆失败
                _states.value = LoginState.loginFailed(e.message)
            }.collect{
                if(it.code === 0){
                    _states.value = LoginState.loginSuccess(it.data)
                }else{//登陆失败
                    _states.value = LoginState.loginFailed(it.msg)
                }
            }
        }
    }
}